package xyz.icxl.kotlion.ext.primitives

import android.content.Context
import android.os.Build
import android.text.Html
import android.text.Spanned
import java.math.BigDecimal
import kotlin.Exception


/**
 * 字符串长度
 *
 * 如果字符串为null 则返回0
 */
val String?.selfLength: Int
    get() = this?.length ?: 0

/**
 * 安全的转换[BigDecimal]
 *
 * 如果字符串是为空或者转换失败返回[BigDecimal.ZERO]
 */
val String?.selfBigDecimal: BigDecimal
    get() {
        return try {
            this?.toBigDecimalOrNull() ?: BigDecimal.ZERO
        } catch (e: Exception) {
            BigDecimal.ZERO
        }
    }

val String?.selfBigDecimalOrNull:BigDecimal?
    get() {
        return try {
            this?.toBigDecimalOrNull()
        } catch (e: Exception) {
            null
        }
    }

val String?.toSelfDouble:Double?
    get() = try {
        this?.toDouble()
    }catch (e:Exception){
        null
    }

/**
 * 安全的把字符串转换为null 如果转换失败返回-1
 */
val String.selfLong:Long
    get() = try {
        this.toLong() ?: 1L
    }catch (e:Exception){
        -1L
    }

fun String.htmlText(context:Context): Spanned {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        return Html.fromHtml(this, Html.FROM_HTML_MODE_COMPACT);
    } else {
        return Html.fromHtml(this)
    }
}